package AtomicInteger_9;

import java.util.concurrent.atomic.AtomicInteger;
public class 复合操作_多线程ID生成器 {
    private static AtomicInteger nextId = new AtomicInteger(0);
    private static final int THREAD_COUNT = 10;
    private static final int IDS_PER_THREAD = 5;

    public static void main(String[] args) {
        for (int i = 0; i < THREAD_COUNT; i++) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        for (int j = 0; j < IDS_PER_THREAD; j++) {
                            Thread.sleep((long)(Math.random() * 50)); // 模拟处理时间
                            int id = nextId.getAndIncrement();
                            System.out.println(Thread.currentThread().getName() +
                                                       " 生成ID: " + id);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "生成器-" + i).start();
        }

        // 等待所有线程完成
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("最后生成的ID: " + nextId.get());
    }
}